﻿'   cftUnity Project browser form
'   Copyright (c) 2010 Marvin Westmaas ( MtM / Marvin_The_Martian )
'
'   This program is free software: you can redistribute it and/or modify
'   it under the terms of the GNU General Public License as published by
'   the Free Software Foundation, either version 3 of the License, or
'   (at your option) any later version.
'
'   This program is distributed in the hope that it will be useful,
'   but WITHOUT ANY WARRANTY; without even the implied warranty of
'   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
'   GNU General Public License for more details.
'
'   You should have received a copy of the GNU General Public License
'   along with this program.  If not, see <http://www.gnu.org/licenses/>.

' projectinfo table name, don't use formatted date string but epoch value???
Public Class frmPBList
#Region "Set form state"
    Public Delegate Sub dWindowState(fState As FormWindowState)
    Public Sub SetWindowState(State As FormWindowState)
        If Me.InvokeRequired Then
            Dim nI As New dWindowState(AddressOf SetWindowState)
            nI.Invoke([State])
        Else
            Me.WindowState = State
        End If
    End Sub
    Public Delegate Sub dSetEnabled(Enabled As Boolean)
    Public Sub SetEnabled(Enabled As Boolean)
        If Me.InvokeRequired Then
            Dim nI As New dSetEnabled(AddressOf SetEnabled)
            nI.Invoke([Enabled])
        Else
            Me.Enabled = Enabled
        End If
    End Sub
#End Region
    Private bAllowClose As Boolean = False
    Private colProjects As New AutoCompleteStringCollection

    Private Sub frmPBList_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If e.CloseReason = CloseReason.WindowsShutDown Or e.CloseReason = CloseReason.ApplicationExitCall Then
            bAllowClose = True
            WriteLog("Application being closed by " & e.CloseReason.ToString)
        End If
        If Not bAllowClose Then
            e.Cancel = True
            Me.Visible = False
            Exit Sub
        End If
    End Sub
    Public Sub CloseForm()
        bAllowClose = True
        Me.Close()
    End Sub
    Public Function FillView() As Boolean
        Try
            Bussy.ShowForm("Sorting.. please wait")
            lvProjects.Items.Clear()
            lvProjects.BeginUpdate()
            colProjects.Clear()
            For xInt As Int32 = 1 To ProjectInfo.Projects.ProjectCount
                Dim Project As clsProjectInfo.sProject.clsProject = ProjectInfo.Projects.Project(ProjectInfo.Projects.ProjectNumber(CShort(xInt)))
                Dim nItem As New ListViewItem
                nItem.Text = Project.ProjectNumber
                nItem.SubItems.Add(Project.ServerIP)
                nItem.SubItems.Add(Project.WUName)
                nItem.SubItems.Add(Project.NumberOfAtoms)
                nItem.SubItems.Add(Project.PreferredDays)
                nItem.SubItems.Add(Project.FinalDeadline)
                nItem.SubItems.Add(Project.Credit)
                nItem.SubItems.Add(Project.Frames)
                nItem.SubItems.Add(Project.Code)
                nItem.SubItems.Add(Project.Contact)
                nItem.SubItems.Add(Project.kFactor)
                'nItem.SubItems.Add(Project.ProjectType.ToString)
                lvProjects.Items.Add(nItem)
                colProjects.Add(Project.ProjectNumber)
                nItem = Nothing
                Project = Nothing
                Application.DoEvents()
            Next
            lvProjects.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
            Dim iWidth(0 To lvProjects.Columns.Count - 1) As Int32, iTotal As Int32 = 0
            For xInt As Int32 = 0 To lvProjects.Columns.Count - 1
                iWidth(xInt) = lvProjects.Columns(xInt).Width
            Next
            lvProjects.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            For xint As Int32 = 0 To lvProjects.Columns.Count - 1
                If lvProjects.Columns(xint).Width < iWidth(xint) Then lvProjects.Columns(xint).Width = iWidth(xint)
            Next
            lvProjects.EndUpdate()
            bNoUpdate = False
            txtFindProject.AutoCompleteCustomSource = colProjects
            lblSummaryInf.Text = lvProjects.Items.Count & " known work units"
            Bussy.CloseForm()
            Return True
        Catch ex As Exception
            Return False
        End Try
    End Function
    Private Sub cmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdClose.Click
        Me.Visible = False
    End Sub
    Private Sub lvProjects_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvProjects.MouseClick
        Try
            Dim lItem As ListViewItem = lvProjects.GetItemAt(e.X, e.Y)
            Try
                If lItem.Text = "" Then Exit Sub
            Catch ex As Exception : End Try
            SelectedProject = ProjectInfo.Projects.Project(lItem.Text)
            If SelectedProject.Description.ToString.ToUpper.Contains("HTTP://") Then
                txtDescription.Text = "This project has not been run yet, projectinfo is only known for projects which you have run locally, there is no code included to parse descriptions from the cgi pages only to read the descriptions from FAHControl.db." & Environment.NewLine & Environment.NewLine & "However, the following link will allow you to read the description at your own discretion, do take note of the recommodation hidden in the URL when doing so." & Environment.NewLine & SelectedProject.Description
            Else
                txtDescription.Text = SelectedProject.Description
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub lvProjects_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvProjects.MouseDoubleClick
        Try
            Dim lItem As ListViewItem = lvProjects.GetItemAt(e.X, e.Y)
            Try
                If lItem.Text = "" Then Exit Sub
            Catch ex As Exception : End Try
            If Not ProjectInfo.Projects.KnownProject(lItem.Text) Then Exit Sub
            Dim eProject As clsProjectInfo.sProject.clsProject = ProjectInfo.Projects.Project(lItem.Text)
            Dim fEdit As New frmEditProject
            fEdit.Text = "Edit project - " & eProject.ProjectNumber
            fEdit.Project = eProject
            AddHandler fEdit.FormClosed, AddressOf EditClosed
            fEdit.ShowDialog(Me)
            fEdit.Dispose()
        Catch ex As Exception
            WriteError("frmPBList_ViewProjectDescription", Err)
        End Try
    End Sub
    Private Sub EditClosed(sender As Object, e As System.EventArgs)
        FillView()
    End Sub
    Private Sub cmdDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdDelete.Click
        Try
            If lvProjects.SelectedItems.Count = 0 Then Exit Sub
            For Each sItem As ListViewItem In lvProjects.SelectedItems
                Dim nProject As clsProjectInfo.sProject.clsProject = ProjectInfo.Projects.Project(sItem.Text)
                Dim rVal As MsgBoxResult = MsgBox("Confirm removal of project - " & nProject.ProjectNumber, MsgBoxStyle.OkCancel, "Remove")
                If Not rVal = MsgBoxResult.Cancel Then
                    If Not ProjectInfo.RemoveProject(nProject.ProjectNumber) Then
                        MsgBox("Removal of project failed for some reason")
                    End If
                End If
            Next
            FillView()
        Catch ex As Exception
            WriteError("frmPBList_ViewProjectDescription", Err)
        End Try
    End Sub
    Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
        Try
            Dim fAdd As New frmAddProject
            AddHandler fAdd.FormClosed, AddressOf Padded
            fAdd.ShowDialog(Me)
            fAdd.Dispose()
        Catch ex As Exception
            WriteError("frmPBList_ViewProjectDescription", Err)
        End Try
    End Sub
    Private Sub Padded(sender As Object, e As System.EventArgs)
        FillView()
    End Sub
    Private SelectedProject As clsProjectInfo.sProject.clsProject
    Private Sub ViewProjectDescriptionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Try
            If SelectedProject.Description <> "" Then
                Process.Start(SelectedProject.Description)
            End If
        Catch ex As Exception
            WriteError("frmPBList_ViewProjectDescription", Err)
        End Try
    End Sub
    Private Sub lvProjects_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvProjects.SelectedIndexChanged
        Try
            ' Look if project number has been run
            txtTPF.Text = "" : txtFindProject.Text = "" : txtPPD.Text = ""
            For Each lvItem As ListViewItem In lvProjects.Items
                If lvItem.Selected Then
                    SelectedProject = projectInfo.Projects.Project(lvItem.Text)
                    Me.Text = "Project summary" & vbTab & " selected-" & SelectedProject.ProjectNumber
                    If SelectedProject.Description.ToString.ToUpper.Contains("HTTP://") Then
                        txtDescription.Text = "This project has not been run yet, projectinfo is only known for projects which you have run locally, there is no code included to parse descriptions from the cgi pages only to read the descriptions from FAHControl.db." & Environment.NewLine & Environment.NewLine & "However, the following link will allow you to read the description at your own discretion, do take note of the recommodation hidden in the URL when doing so." & Environment.NewLine & SelectedProject.Description
                    Else
                        txtDescription.Text = SelectedProject.Description
                    End If
                    Exit Try
                End If
            Next
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub txtDescription_LinkClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.LinkClickedEventArgs) Handles txtDescription.LinkClicked
        Try
            Process.Start(e.LinkText)
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click
        Try
            If txtURL.TextLength = 0 Then
                txtURL.Focus()
                Exit Sub
            End If
            Dim oProjects As clsProjectInfo.sProject = projectInfo.Projects
            If projectInfo.GetProjects(txtURL.Text, True) Then
                ' sqData.Update_ProjectInfo(projectInfo, DateTime.Now.ToString(Format(strDTFormat)))
                projectInfo = sqData.Update_ProjectInfo(projectInfo)
                Dim rVal As MsgBoxResult = MsgBox("Do you want to check the database for work units which were unknown and can now be credited?", CType(MsgBoxStyle.Question + MsgBoxStyle.OkCancel, MsgBoxStyle))
                If rVal = MsgBoxResult.Ok Then
                    WriteLog("Trying to recredit the database.. " & sqData.RecreditAllWorkUnits.ToString)
                End If
                FillView()
            Else
                projectInfo.Projects = oProjects
            End If
            oProjects = Nothing
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private bNoUpdate As Boolean = False
    Private Sub txtFindProject_KeyUp(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtFindProject.KeyUp
        'Ideally posisble input should be limited to the autocomplete source?
        Try
            If txtFindProject.TextLength = 0 Then Exit Sub
            If e.KeyCode <> Keys.Enter Then Exit Sub
            For Each lItem As ListViewItem In lvProjects.Items
                If lItem.Text = txtFindProject.Text Then
                    lItem.Selected = True
                    lvProjects.Select()
                    lItem.EnsureVisible()
                    Exit For
                End If
                Application.DoEvents()
            Next
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub txtTPF_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtTPF.KeyDown
        Try
            If lvProjects.SelectedItems.Count = 0 Then
                txtTPF.Text = ""
                e.SuppressKeyPress = True
                Exit Sub
            End If
            If e.KeyData = Keys.Delete Or e.KeyData = Keys.Back Then
                e.SuppressKeyPress = True
                txtTPF.Text = ""
            ElseIf Not (e.KeyData >= Keys.D0 And e.KeyData <= Keys.D9) And Not (e.KeyData >= Keys.NumPad0 And e.KeyData <= Keys.NumPad9) Then
                e.SuppressKeyPress = True
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Function CalcPPF_TPF() As String
        Try
            Dim iHours As Int32 = CInt(txtTPF.Text.Substring(0, 2))
            Dim iMinutes As Int32 = CInt(txtTPF.Text.Substring(3, 2))
            Dim iSeconds As Int32 = CInt(txtTPF.Text.Substring(6, 2))
            Dim tsFrame As New TimeSpan(iHours, iMinutes, iSeconds)
            Dim tsCompletion As TimeSpan = TimeSpan.FromTicks((tsFrame.Ticks * 100))
            Dim sPPD As clsProjectInfo.sProjectPPD = projectInfo.GetEffectivePPD_sqrt(DateTime.Now, DateTime.Now.Add(tsCompletion), lvProjects.SelectedItems(0).Text)
            Return sPPD.PPD
        Catch ex As Exception
            WriteError(ex.Message, Err)
            Return "*"
        End Try
    End Function
    Private Sub txtTPF_TextChanged(sender As Object, e As System.EventArgs) Handles txtTPF.TextChanged
        Try
            If txtTPF.TextLength = 2 Then
                txtTPF.Text &= ":"
                txtTPF.SelectionStart = 3
            ElseIf txtTPF.TextLength = 5 Then
                txtTPF.Text &= ":"
                txtTPF.SelectionStart = 6
            ElseIf txtTPF.TextLength = 8 Then
                txtPPD.Text = CalcPPF_TPF()
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub

    Private Sub frmPBList_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Try


        Catch ex As Exception

        End Try
    End Sub
End Class

